﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using XF.FM.Core.Auth;
using XF.FM.Simple.Models;

namespace XF.FM.Simple.Controllers
{
    public class AccountController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
        [HttpGet]
        public IActionResult Login(string returnUrl)
        {
            ViewData["ReturnUrl"] = returnUrl;
            return View();
        }
        [HttpPost]
        public async Task<IActionResult> Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                int userId = 1;
                await HttpContext.XfSignInAsync(userId, model.UserName, "gust").ConfigureAwait(false);
                if (string.IsNullOrEmpty(returnUrl))
                    return RedirectToAction(nameof(Info));
                else
                    return Redirect(returnUrl);
            }
            return View(model);
        }
        public async Task<IActionResult> Logout()
        {
            await HttpContext.XfSignOutAsync().ConfigureAwait(false);
            return RedirectToAction(nameof(Login));
        }
        public IActionResult Denied(string returnUrl)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (Request.Headers.TryGetValue("Referer", out StringValues url))
            {
                ViewData["url"] = url;
            }
            return View();
        }
        [Authorize]
        public IActionResult Info()
        {
            return View();
        }
    }
}